package com.kingsoft.miot.bridge.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.ISelect;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kingsoft.miot.bridge.pojo.house.HouseVo;
import com.kingsoft.miot.bridge.utils.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.kingsoft.miot.bridge.controller.req.OrderBy;
import com.kingsoft.miot.bridge.controller.resp.HouseInfoResp;
import com.kingsoft.miot.bridge.controller.resp.PageResult;
import com.kingsoft.miot.bridge.dao.HotelInfoDao;
import com.kingsoft.miot.bridge.dao.HouseInfoDao;
import com.kingsoft.miot.bridge.dao.PageBean;
import com.kingsoft.miot.bridge.exception.CommonException;
import com.kingsoft.miot.bridge.pojo.hotel.HotelInfo;
import com.kingsoft.miot.bridge.pojo.hotel.HouseInfo;
import com.kingsoft.miot.bridge.service.HouseService;
import org.springframework.ui.ModelMap;

/**
 * 家庭 （户） 服务
 *
 * @author melody
 */
@Service
public class HouseServiceImpl implements HouseService {

    private static final Logger LOGGER = LoggerFactory.getLogger(HouseServiceImpl.class);

    @Autowired
    private HouseInfoDao houseInfoDao;

    @Autowired
    private HotelInfoDao hotelInfoDao;

    @Override
    public void insertOne(HouseInfo houseInfo) {


    }

    @Override
    public HouseInfo getByHouseInfoId(int room_info_id) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<HouseInfo> getListByHotelInfoId(int hotel_info_id) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<HouseInfo> findAll() {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 通过hotel id 和 house id 获取house 信息
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public HouseInfoResp getByHotelInfoIdAndHouseInfoId(int hotel_info_id, int house_info_id) {
        try {
            // 1. 查询是否存在hotel
            HotelInfo hotelInfo = hotelInfoDao.getById(hotel_info_id);
            if (hotelInfo == null) {
                throw new CommonException("获取house失败，不存在该hotel");
            }
            // 2. 查询是否存在house
            Map<String, Integer> argMap = new HashMap<>();
            argMap.put("hotel_info_id", hotel_info_id);
            argMap.put("house_info_id", house_info_id);
            HouseInfo houseInfo = houseInfoDao.getByHotelIdAndHouseId(argMap);
            HouseInfoResp houseInfoResp = new HouseInfoResp();
            if (houseInfo != null) {
                populateDataToResp(houseInfo, houseInfoResp);
            }
            return houseInfoResp;
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("通过hotel id 和 house id获取失败。");
            throw new CommonException("通过hotel id 和 house id获取失败。");
        }

    }

    /**
     * 查询 分页查询所有house
     */
    @Override
    public PageResult<HouseInfoResp> findHouseByPageAndhotelId(int hotel_info_id, int currentPage, int pageSize,
                                                               int room_num, List<OrderBy> orderByList) {

        // 设置分页信息，分别是当前页数和每页显示的总记录数 -->记住：必须在mapper接口中的方法执行之前设置该分页信息
//		PageHelper.startPage(currentPage, pageSize);
        // 暂时查询总记录数
        List<HouseInfo> allHouse = houseInfoDao.findAll(); // 全部商品
//		System.out.println(allHouse);
        int countNums = allHouse.size(); // 总记录数
        PageBean<HouseInfo> pageData = new PageBean<>(currentPage, pageSize, countNums);
        pageData.setItems(allHouse);
        PageResult<HouseInfoResp> pageResult = new PageResult<HouseInfoResp>();
        pageResult.setCurrent_page(currentPage);
        pageResult.setSize(pageSize);
        pageResult.setTotal_count(countNums);
        pageResult.setTotal_pages(pageData.getTotalPage());

        // 直接查询房间信息
        if (room_num > 0) {
            HouseInfo h1 = houseInfoDao.getByHouseInfoNum(room_num);
            ArrayList<HouseInfoResp> retList = new ArrayList<HouseInfoResp>();
            if (h1 != null) {
                HouseInfoResp resp = new HouseInfoResp();
                populateDataToResp(h1, resp);
                retList.add(resp);
            }
            pageResult.setItem_list(retList);
            // 只查询一条数据 并返回
            return pageResult;
        }
        // 起始也
        int start = (currentPage - 1) * pageSize >= allHouse.size() ? (allHouse.size() / pageSize) * pageSize
                : (currentPage - 1) * pageSize;
        // 最终页
        int end = currentPage * pageSize >= allHouse.size() ? allHouse.size() : currentPage * pageSize;
        // 添加并转化数据
        List<HouseInfo> subList = allHouse.subList(start, end);
        ArrayList<HouseInfoResp> retList = new ArrayList<HouseInfoResp>();
        for (HouseInfo houseInfo : subList) {
//			System.out.println(houseInfo);
            HouseInfoResp resp = new HouseInfoResp();
            populateDataToResp(houseInfo, resp);
            retList.add(resp);
        }
        pageResult.setItem_list(retList);
        return pageResult;
    }

    /**
     * 填充数据到房间信息数据
     *
     * @param dest
     * @param target
     */
    private void populateDataToResp(HouseInfo dest, HouseInfoResp target) {
        // 房屋状态
        short statusNum = dest.getHouse_info_status();
        Map<String, Object> dataMap = new HashMap<>();
        if (statusNum == 1) {
            dataMap.put("name", "使用中");
            dataMap.put("value", 1);
        } else if (statusNum == 0) {
            dataMap.put("name", "空房");
            dataMap.put("value", 0);
        } else {
            dataMap.put("name", "已停用");
            dataMap.put("value", -1);
        }
        target.setId(dest.getHotel_info_id());
        target.setRoom_num(dest.getHouse_info_num());
        target.setControl_id(dest.getControl_unit_id());
        target.setFloors_total_num(dest.getHouse_info_floors_total_num());
        target.setDevices_total_num(dest.getHouse_info_devices_total_num());
        target.setDevices_online_num(dest.getHouse_info_devices_online_num());
        target.setUser(dest.getUser_mobile());
        target.setStatus(dataMap);
        target.setControl_times(dest.getHouse_info_control_times());
        target.setControl_history_times(dest.getHouse_info_history_times());
        // 上次登录时间
        target.setLast_login_time(new Date().getTime());
        // 上次操作时间
        target.setLast_operate_time(new Date().getTime());
    }


    /**
     * 查询房间列表(根据房间号等信息)
     *
     * @param params
     * @return
     */
    @Override
    public ModelMap findHouseListByHouseNo(JSONObject params) {
        Integer page = params.getInteger("page");
        Integer size = params.getInteger("size");
        Integer hotelId = params.getInteger("id");
        Integer room_num = params.getInteger("room_num");
        /** 临时注解*/
//        JSONArray orders = params.getJSONArray("orders");
//        JSONObject typeJson = JSONObject.parseObject(orders.get(0).toString());
        Map<String, Object> condition = new HashMap<>();
        condition.put("houseNo", room_num);
        condition.put("hotelId", hotelId);
        PageInfo<HouseInfo> houseInfoPageInfo = PageHelper.startPage(page, size)
                .doSelectPageInfo(new ISelect() {
                    @Override
                    public void doSelect() {
                        houseInfoDao.findHouseListByHouseNo(condition);
                    }
                });
        List<HouseVo> houseVos = houseInfoPageInfo.getList().stream().map(e -> new HouseVo(e.getHouse_info_id(),
                e.getHouse_info_num(), e.getControl_unit_id(), e.getHouse_info_floors_total_num(),
                e.getHouse_info_devices_total_num(), e.getHouse_info_devices_online_num(),
                e.getUser_mobile(), e.getHouse_info_status() == 0 ? ValidationUtils.getHouseStatus(0) : ValidationUtils.getHouseStatus(1), e.getHouse_info_control_times(),
                e.getHouse_info_history_times())).collect(Collectors.toList());
        ModelMap modelMap = new ModelMap();
        modelMap.put("total_pages", houseInfoPageInfo.getPages());
        modelMap.put("total_count", houseInfoPageInfo.getTotal());
        modelMap.put("current_page", houseInfoPageInfo.getPageNum());
        modelMap.put("size", houseInfoPageInfo.getPageSize());
        modelMap.put("item_list", houseVos);
        return modelMap;
    }

    /**
     * 添加房间
     *
     * @param params
     * @return
     */
    @Override
    public int insertBathHouse(JSONObject params) {
        String houseNum = params.getString("house_num");
        Integer houseStatus = params.getInteger("house_status");
        Integer hotelId = params.getInteger("hotel_id");
        Integer floorsTotalNum = params.getInteger("floors_total_num");
        Integer devicesTotalNum = params.getInteger("devices_total_num");
        Integer devicesOnlineNum = params.getInteger("devices_online_num");
        List<HouseInfo> houseInfos = new ArrayList<>();
        HouseInfo houseInfo = new HouseInfo();
        houseInfo.setControl_unit_id(213121321);
        houseInfo.setHouse_info_control_times(0);
        houseInfo.setHouse_info_history_times(0);
        houseInfo.setHotel_info_id(hotelId);
        houseInfo.setHouse_info_floors_total_num(floorsTotalNum);
        houseInfo.setHouse_info_devices_total_num(devicesTotalNum);
        houseInfo.setHouse_info_devices_online_num(devicesOnlineNum);
        houseInfo.setHouse_info_num(Integer.valueOf(houseNum));
        houseInfo.setHouse_info_status(Short.parseShort(houseStatus.toString()));
        houseInfos.add(houseInfo);
        int count = houseInfoDao.insertBatchHouse(houseInfos);
        if (count != 0) {
            return 1;
        }
        return 0;
    }

    /**
     * 根据房间ID查询某一个房间
     *
     * @param hotelId
     * @param houseId
     * @return
     */
    @Override
    public HouseInfo findHouseByHouseId(Integer hotelId, Integer houseId) {
        return houseInfoDao.findHouseByHouseId(hotelId, houseId);
    }

}
